//
//  DownLRCManager.m
//  MiBaoTu
//
//  Created by admin on 16/10/24.
//  Copyright © 2016年 com.caesartech15. All rights reserved.
//

#import "DownLRCManager.h"

@interface DownLRCManager ()<NSURLSessionDelegate> {
    NSString        *_url;
    NSString        *_musicFullName;
    NSInteger       totalLength;
}

@end
@implementation DownLRCManager {
    NSOutputStream          *outStream;
}

+ (instancetype)staredInstance
{
    static DownLRCManager *downManager = nil;
    static dispatch_once_t onceToken;
    dispatch_once(&onceToken, ^{
        downManager = [[self alloc]init];
    });
    return downManager;
}

#pragma mark - 开始下载
- (void)downloadWithUrl:(NSString *)urlString
          withMusicName:(NSString *)musicFullName
{
    if (!urlString) {
        return;
    }
    _url = urlString;
    _musicFullName = musicFullName;
    
    //创建缓存地址
    [self onCreateCacheDirectory];
    //创建输出流
    NSString *musicName = [musicFullName componentsSeparatedByString:@"."][0];
    NSString *filePath = [MusicCachesDirectory stringByAppendingPathComponent:[NSString stringWithFormat:@"%@.lrc",musicName]];
//    NSString *filePath = [MusicCachesDirectory stringByAppendingPathComponent:[NSString stringWithFormat:@"%@.text",musicName]];
    NSFileManager *fileManager = [NSFileManager defaultManager];
    if ([fileManager fileExistsAtPath:filePath]) {
        return;
    }
    outStream = [NSOutputStream outputStreamToFileAtPath:filePath append:YES];
    
    NSURLSession *session = [NSURLSession sessionWithConfiguration:[NSURLSessionConfiguration defaultSessionConfiguration] delegate:self delegateQueue:[[NSOperationQueue alloc] init]];
    
    //请求 range请求头必写，断点续传效果
    NSURL *url = [NSURL URLWithString:[urlString stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding]];
    NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:url];
    NSString *range = [NSString stringWithFormat:@"bytes=%zd-",DownloadLength(filePath)];
    [request setValue:range forHTTPHeaderField:@"Range"];
    NSURLSessionDataTask *task = [session dataTaskWithRequest:request];
    
    //开始下载
    [task resume];
}

#pragma mark - Actions
//创建下载缓存目录地址
- (void)onCreateCacheDirectory
{
    NSFileManager *fileManager = [NSFileManager defaultManager];
    if (![fileManager fileExistsAtPath:MusicCachesDirectory]) {
        [fileManager createDirectoryAtPath:MusicCachesDirectory withIntermediateDirectories:YES attributes:nil error:NULL];
    }
}

#pragma mark NSURLSessionDataDelegate

/**
 * 接收到响应
 */
- (void)URLSession:(NSURLSession *)session
          dataTask:(NSURLSessionDataTask *)dataTask
didReceiveResponse:(NSHTTPURLResponse *)response
 completionHandler:(void (^)(NSURLSessionResponseDisposition))completionHandler
{
    // 接收这个请求，允许接收服务器的数据
    if (outStream) {
        [outStream open];
    }
    
    //本地已下载的和服务器未下载下来的总数据
    NSString *musicName = [_musicFullName componentsSeparatedByString:@"."][0];
    NSString *filePath = [MusicCachesDirectory stringByAppendingPathComponent:[NSString stringWithFormat:@"%@.lrc",musicName]];
    totalLength = [response.allHeaderFields[@"Content-Length"] integerValue] + DownloadLength(filePath);
    
    completionHandler(NSURLSessionResponseAllow);
}

/**
 * 接收到服务器返回的数据
 */
- (void)URLSession:(NSURLSession *)session
          dataTask:(NSURLSessionDataTask *)dataTask
    didReceiveData:(NSData *)data
{
    //写入数据
    [outStream write:data.bytes maxLength:data.length];
}

/**
 * 请求完毕（成功|失败）
 */
- (void)URLSession:(NSURLSession *)session
              task:(NSURLSessionTask *)task
didCompleteWithError:(NSError *)error
{
    //流关闭
    if (outStream) {
        [outStream close];
        outStream = nil;
    }
    
    
    NSString *musicName = [_musicFullName componentsSeparatedByString:@"."][0];
    NSString *filePath = [MusicCachesDirectory stringByAppendingPathComponent:[NSString stringWithFormat:@"%@.lrc",musicName]];
    if (totalLength == DownloadLength(filePath)) {
        NSLog(@"yes");
    }
}

@end
